﻿using Module_Debug.Hardware;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.IO.Ports;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using ComPortUser;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
namespace Module_Debug
{
    public partial class LIR_RCH : Form
    {


        #region LIR_RCH 初始化串口
        public comPort com;    //串口
        private void Form1_Load() //窗体导入函数 初始化
        {
            com = new comPort();
            thread_init(); //线程初始化
        }
        #endregion

        #region 打开/关闭串口
        // 获取串口号
        private void cbxPort_Click(object sender, EventArgs e)
        {
            com.cbxGetName(cbxPort);
        }
        private bool isConnect = false;
        private void buttonConnect_Click(object sender, EventArgs e)
        {
            if (isConnect == false) //打开串口
            {
                if (com.SetPortProperty(cbxPort.Text))
                {
                    cbxPort.Enabled = false;
                    buttonConnect.Text = "断开";
                    dat_para.Start();
                    // tbxKey.Text = "KShuachen123456";
                }
                isConnect = true;
            }
            else  //关闭串口
            {
                if (com.ClosePort())
                {
                    cbxPort.Enabled = true;
                    buttonConnect.Text = "连接";
                }
                isConnect = false;
            }
        }
        #endregion

        #region 串口接收 线程相关

        #region 线程初始化
        public System.Threading.Thread dat_para;
        public void thread_init()
        {
            dat_para = new System.Threading.Thread(Get_Dat);
            dat_para.IsBackground = true;
        }
        #endregion

        #region 串口接收 提取数据：放在线程dat_para中
        public const UInt16 TranInfoCmd = 0x0106;
        public const UInt16 channel_Raw_data = 0x0107; //10通道原始数据
        public int num = 0;

        byte[] dat = new byte[500];
        public bool isDataRight = true;
        Int32 xxx;
        Int32 yyy;
        Int32 control_flag;
        //坐标系
        double[] coordinates_x = new double[100];
        double[] coordinates_y = new double[100];
        double x_point = 0, y_point = 0;
        //CA410
        int interval_delayms = 0;
        int interval_times = 0;
        int start_flag = 0;
        int start_x = 0; //实时坐标点
        int start_y = 0; //实时坐标点
        int X_mm_pulse = 132;//39500 pulse=300mm
        int Y_mm_pulse = 132;//39500 pulse=300mm
        int counts = 0;
        int receive_delay = 0;
        public void Get_Dat()
        {
            while (true)
            {
                if (com.receive_flag == true)
                {
                    isDataRight = true;
                    dat[0] = (byte)(com.frmFmt_1.flag);
                    dat[1] = (byte)(com.frmFmt_1.SrcAddr >> 8);
                    dat[2] = (byte)(com.frmFmt_1.SrcAddr);
                    dat[3] = (byte)(com.frmFmt_1.DestAddr >> 8);
                    dat[4] = (byte)(com.frmFmt_1.DestAddr);
                    dat[5] = (byte)(com.frmFmt_1.Type);
                    dat[6] = (byte)(com.frmFmt_1.Length);
                    for (int i = 0; i < dat[6]; i++) dat[i + 7] = (byte)(com.frmFmt_1.buf[i]);
                    if ((com.frmFmt_1.verify == com.get_crc(dat, (byte)(com.frmFmt_1.Length + 7))) && isDataRight)
                    {
                        xxx = (com.frmFmt_1.buf[0] << 24) | (com.frmFmt_1.buf[1] << 16) | (com.frmFmt_1.buf[2] << 8) | (com.frmFmt_1.buf[3] << 0);
                        yyy = (com.frmFmt_1.buf[4] << 24) | (com.frmFmt_1.buf[5] << 16) | (com.frmFmt_1.buf[6] << 8) | (com.frmFmt_1.buf[7] << 0);
                        control_flag = com.frmFmt_1.buf[8];
                    }
                    com.receive_flag = false;
                }
            }
        }
        #endregion
        private void Aoto_measure()
        {
            if (start_flag != 0)
            {

                switch (start_flag)
                {
                    case 1://移动点位
                        XYZ_move((Int32)(coordinates_x[start_x] * X_mm_pulse), (Int32)(coordinates_y[start_y] * Y_mm_pulse));
                        start_flag = 2;
                        receive_delay = 5;
                        break;
                    case 2://判断是是否到位置
                        if (receive_delay > 0) receive_delay--;
                        else
                        {
                            if (control_flag == 0) start_flag = 3;
                        }
                        break;
                    case 3://测量
                        CA410_measurement();
                        start_flag = 1;
                        if (start_x < x_point) start_x++;
                        if (start_x == x_point)
                        {
                            start_x = 0;
                            start_y++;
                        }
                        if (start_y == y_point)
                        {
                            start_flag = 0;//结束
                            MessageBox.Show("测量结束");
                        }

                        break;

                }
            }
        }
        private void CA410_measurement()
        {
            for (int ii = 0; ii < interval_times; ii++)
            {
                Thread.Sleep(interval_delayms);
                Msr_CA310();
                Msr_CA310(); //修复讨厌的灰阶跳变时CA410数据异常的问题
                CAS200_dataGridView.ClearSelection();//清空
                CAS200_dataGridView.Rows.Add();
                CAS200_dataGridView.Rows[counts].Cells[0].Value = counts.ToString();//no.
                CAS200_dataGridView.Rows[counts].Cells[1].Value = auto_x.ToString().Substring(0, 6);
                CAS200_dataGridView.Rows[counts].Cells[2].Value = auto_y.ToString().Substring(0, 6);
                CAS200_dataGridView.Rows[counts].Cells[3].Value = auto_lum.ToString().Substring(0, 6);
                counts++;
            }
        }
        private void T7_Tick(object sender, EventArgs e)
        {
            xxx_text.Text = ((double)xxx / X_mm_pulse).ToString("F2");
            yyy_text.Text = ((double)yyy / Y_mm_pulse).ToString("F2");
            control_flag_text.Text = control_flag.ToString();
            point_X.Text = start_x.ToString();
            point_Y.Text = start_y.ToString();
            Aoto_measure();
        }
        private void XYZ_move(Int32 xxx, Int32 yyy)
        {
            byte[] cmd = { 0x7F, 0x00, 0x00, 0x00, 0x00, 0x01, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
            cmd[7] = (byte)(xxx >> 24);
            cmd[8] = (byte)(xxx >> 16);
            cmd[9] = (byte)(xxx >> 8);
            cmd[10] = (byte)(xxx >> 0);
            cmd[11] = (byte)(yyy >> 24);
            cmd[12] = (byte)(yyy >> 16);
            cmd[13] = (byte)(yyy >> 8);
            cmd[14] = (byte)(yyy >> 0);
            com.RS232_Send(cmd);
            // MessageBox.Show("发送XYZ");
        }
        private void XYZ_Click(object sender, EventArgs e)
        {
            Button btnTmp = (Button)sender;
            Int32 xxx = Convert.ToInt32(xxx_in.Text) * X_mm_pulse;
            Int32 yyy = Convert.ToInt32(yyy_in.Text) * Y_mm_pulse;
            switch (btnTmp.Name)
            {
                case "origin":
                    xxx = 0;
                    yyy = 0;
                    break;
            }
            XYZ_move(xxx, yyy);

            // MessageBox.Show("发送XYZ");
        }
        private void Stop_Click(object sender, EventArgs e)
        {
            start_flag = 0;//结束
            byte[] cmd = { 0x7F, 0x00, 0x00, 0x00, 0x00, 0xFE, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
            com.RS232_Send(cmd);
        }
        private void compute_Click(object sender, EventArgs e)
        {
            x_point = Convert.ToDouble(x_Block.Text);
            y_point = Convert.ToDouble(y_Block.Text);
            double x_div = Convert.ToDouble(x_length.Text) / (x_point - 1);
            double y_div = Convert.ToDouble(y_length.Text) / (y_point - 1);
            for (int xx = 0; xx < x_point; xx++)
            {
                coordinates_x[xx] = xx * x_div;
            }
            for (int yy = 0; yy < y_point; yy++)
            {
                coordinates_y[yy] = yy * y_div;
            }
            txttip.Text += "计算坐标完成\r\n";
        }
        private void start_measure_Click(object sender, EventArgs e)
        {
            interval_delayms = Convert.ToInt32(interval.Text);
            interval_times = Convert.ToInt32(times.Text);
            start_x = 0; //实时坐标点
            start_y = 0; //实时坐标点
            start_flag = 1;
            counts = 0;
            txttip.Text += "开始走位\r\n";
        }
        private void measure_Click(object sender, EventArgs e)
        {
            Thread.Sleep(10);
            Msr_CA310();
            Msr_CA310(); //修复讨厌的灰阶跳变时CA410数据异常的问题
            CAS200_dataGridView.ClearSelection();//清空
            CAS200_dataGridView.Rows.Add();
            CAS200_dataGridView.Rows[counts].Cells[0].Value = counts.ToString();//no.
            CAS200_dataGridView.Rows[counts].Cells[1].Value = auto_x.ToString().Substring(0, 6);
            CAS200_dataGridView.Rows[counts].Cells[2].Value = auto_y.ToString().Substring(0, 6);
            CAS200_dataGridView.Rows[counts].Cells[3].Value = auto_lum.ToString().Substring(0, 6);
            counts++;
        }
        private void btn_CAS200_Synt_Click(object sender, EventArgs e)
        {
            Button btnTmp = (Button)sender;
            Application.DoEvents();
            switch (btnTmp.Name)
            {
                case "btn_CAS200Save":
                    {
                        SaveFileDialog sf = new SaveFileDialog(); //对话框
                        sf.Filter = @"csv文件(*.csv)|*.csv|所有文件(*.*)|*.*"; //定义保存的文件的类型

                        string str = "序号,x坐标,y坐标,亮度\r\n";

                        if (sf.ShowDialog() == DialogResult.OK) //如果确定保存
                        {
                            if (sf.FileName == "") return; //如果没有输入文件名
                            try
                            {
                                StreamWriter sw = null; //文件流
                                sw = new StreamWriter(sf.FileName, false, Encoding.UTF8);
                                for (int i = 0; i < (this.CAS200_dataGridView.Rows.Count - 1); i++)
                                {
                                    str = str + this.CAS200_dataGridView.Rows[i].Cells[0].Value.ToString() + ","
                                        + this.CAS200_dataGridView.Rows[i].Cells[1].Value.ToString() + ","
                                        + this.CAS200_dataGridView.Rows[i].Cells[2].Value.ToString() + ","
                                        + this.CAS200_dataGridView.Rows[i].Cells[3].Value.ToString();

                                    str = str + "\r\n";
                                }
                                sw.WriteLine(str);
                                sw.Dispose(); //释放资源
                                sw.Close(); //关闭数据流
                                MessageBox.Show("测试数据保存OK！", "系统提示：");
                            }
                            catch
                            {
                                MessageBox.Show("测试数据保存时发生错误，请再试！", "系统提示：");
                            }
                        }
                    }
                    break;
                case "btn_CAS200_Clean":
                    {
                        CAS200_dataGridView.Rows.Clear();
                        counts = 0;
                    }
                    break;
                default: break;
            }
        }
        #endregion


        #region 子窗口
        CRC16 CRCData = new CRC16();

        private byte[] Send_buf = new byte[1];

        private List<string> ImageType;

        public static bool firstGammaFlag = true;   //初次打开子窗体标志位
        frmMain frmTop = null;

        public LIR_RCH(frmMain SX_LIR_RCH)
        {
            Form1_Load();
            frmTop = SX_LIR_RCH;
            InitializeComponent();
            frmTop.Child_window_hide_already = true;
            frmTop.Child_Gamma_Window_Open_Enable = false;//防止重复开启子窗体  

            string[] s = { ".bmp" };
            this.ImageType = new List<string>(s);
        }

        #endregion

        #region   //=================================LCD cfg function:OLED_Show_Click====Start=================

        private void OLED_Show_Click(object sender, EventArgs e)
        {
            byte[] TepArr;
            Button btnTmp = (Button)sender;

            Send_buf = new byte[25];

            Setting.TempRecord.cmdLen = 25;

            Send_buf[0] = 0x0A; //LCD配置标志
            Send_buf[2] = 0x15; //数据长度
            switch (btnTmp.Name)
            {
                case "btnPatternW":                             //写入Pattern参数
                    {
                        Send_buf[1] = 0x07;
                        Send_buf[3] = byte.Parse(numPatternR.Value.ToString());
                        Send_buf[4] = byte.Parse(numPatternG.Value.ToString());
                        Send_buf[5] = byte.Parse(numPatternB.Value.ToString());
                    }
                    break;
                case "btnred":
                    {
                        Send_buf[1] = 0x07;
                        Send_buf[3] = 0xFF;
                        Send_buf[4] = 0;
                        Send_buf[5] = 0;
                    }
                    break; //R
                case "btngreen":
                    {
                        Send_buf[1] = 0x07;
                        Send_buf[3] = 0;
                        Send_buf[4] = 0xFF;
                        Send_buf[5] = 0;
                    }
                    break; //G
                case "btnblue":
                    {
                        Send_buf[1] = 0x07;
                        Send_buf[3] = 0;
                        Send_buf[4] = 0;
                        Send_buf[5] = 0xFF;
                    }
                    break; //B
                case "btnwhite":
                    {
                        Send_buf[1] = 0x07;
                        Send_buf[3] = 0xFF;
                        Send_buf[4] = 0xFF;
                        Send_buf[5] = 0xFF;
                    }
                    break; //W
                case "btnblack":
                    {
                        Send_buf[1] = 0x07;
                        Send_buf[3] = 0;
                        Send_buf[4] = 0;
                        Send_buf[5] = 0;
                    }
                    break; //BL
                default:
                    break;
            }

            CRCData.CalculateCrc16(Send_buf, out Send_buf[23], out Send_buf[24]);
            try
            {
                frmTop.comPort.Write(Send_buf, 0, 25);
            }
            catch
            {
                MessageBox.Show("OLED_Show串口有误，请检查", "错误");
            }



        }


        #endregion //=================================LCD cfg function: OLED_Show_Click====end=================     

        #region  //-- 无用   以及 串口 返回数据 处理- --- serial Data----
        private void LIR_RCH_FormClosed(object sender, FormClosedEventArgs e)
        {
            ////frmTop.comPort.Close()
            ////frmTop.comPort.Open();
            frmTop.textBox1.Text = frmTop.textBox1.Text + "LIR_RCH_FormClosed！\r\n";
            frmTop.Child_Gamma_Window_Open_Enable = true; //允许其他子窗体打开
            frmTop.Child_window_hide_already = false;
            frmTop.IC_comboBox.Enabled = true;
            firstGammaFlag = true;
        }
        private void LIR_RCH_VisibleChanged(object sender, EventArgs e)
        {
            if (frmTop.Child_window_hide_already == false) //子窗体已开启标识
            {
                ////frmTop.comPort.Close()

                ////frmTop.comPort.Open();
                frmTop.textBox1.Text = frmTop.textBox1.Text + "LIR_RCH_FormHide！\r\n";
                frmTop.Child_window_hide_already = true; //子窗体已隐藏标识
            }
            else
            {

                frmTop.textBox1.Text = frmTop.textBox1.Text + "IC69310_Gamma_FormOpened！\r\n";
                frmTop.Child_window_hide_already = false; //子窗体已开启标识
            }

        }
        #endregion //---串口返回数据处理- --- serial Data----

        #region    //---CA410----------------------

        private double auto_lum;  //  存放获取到的产品亮度值
        private double auto_x;
        private double auto_y;        //  存放获取到的产品亮度 色坐标 x,y



        private void Msr_CA310()
        {
            frmTop.Msr_CASDK();
            auto_lum = frmTop.CASDK_LUM;
            auto_x = frmTop.CASDK_x;
            auto_y = frmTop.CASDK_y;
            lab_CASDK_Lv.Text = auto_lum.ToString().Substring(0, 6);
            lab_CASDK_Sx.Text = auto_x.ToString().Substring(0, 6);
            lab_CASDK_Sy.Text = auto_y.ToString().Substring(0, 6);
        }   //获取CA310/CA410读数




        #region  //Gamma调整计时
        System.DateTime TimeNow = new DateTime();
        TimeSpan TimeCount = new TimeSpan();
        private void TimTest_Tick(object sender, EventArgs e)
        {
            TimeCount = DateTime.Now - TimeNow;
        }
        #endregion
        private byte[] arrbyte_tmp = new byte[250];         //临时保存下位机返回值

        #endregion  //--- Auto Gamma-----

        string path = "";
        #region //------自定义功能按键---------------

        //------------------------------------------------------------

        private void LIR_RCH_FormClosing(object sender, FormClosingEventArgs e)
        {
            e.Cancel = true;
            this.Hide();
        }


        #endregion
        #region    //浏览图片
        //string path = "";
        private void btnBrowsePic_Click(object sender, EventArgs e)    //载入画面按键  选择文件夹
        {
            if (txtbmp.Text != "")
            {
                frmTop.defaultfilePath = txtbmp.Text;
            }
            else
            {
                StreamReader streamReader = new StreamReader("./update/Picaddr.txt", Encoding.Default);
                frmTop.defaultfilePath = streamReader.ReadLine();
                streamReader.Close();
            }
            FolderBrowserDialog fldb = new FolderBrowserDialog();
            //首次defaultfilePath为空，按FolderBrowserDialog默认设置（即桌面）选择            
            if (frmTop.defaultfilePath != "")
            {
                //设置此次默认目录为上一次选中目录
                fldb.SelectedPath = frmTop.defaultfilePath;
            }

            fldb.ShowNewFolderButton = false;
            DialogResult res = fldb.ShowDialog();
            if (res != System.Windows.Forms.DialogResult.OK)
            {
                MessageBox.Show("没选择任何文件夹.");
                return;
            }
            frmTop.defaultfilePath = fldb.SelectedPath;
            path = fldb.SelectedPath;
            if (!Directory.Exists(path))
            {
                MessageBox.Show("文件夹不存在.");
                return;
            }
            DirectoryInfo di = new DirectoryInfo(path);
            this.listBox3_BMPFile.Items.Clear();
            this.CreateListItem(di);//递归加载文件夹里的所有图片
            txtbmp.Text = path;
            // -------------------------------------------------------------------------
            StreamWriter sw = null; //文件流
            sw = new StreamWriter("./update/Picaddr.txt", false, Encoding.Default);//Encoding.GetEncoding("UTF-8")
            sw.Write(frmTop.defaultfilePath);
            sw.Dispose(); //释放资源
            sw.Close(); //关闭数据流
        }
        /// <summary>
        /// 递归文件夹，把文件夹里所有后缀类似图片的文件，加入listbox
        /// </summary>
        /// <param name="di"></param>
        private void CreateListItem(DirectoryInfo di)
        {
            foreach (DirectoryInfo childDi in di.GetDirectories())
            {
                this.CreateListItem(childDi);
            }

            foreach (FileInfo fi in di.GetFiles())
            {
                if (ImageType.Contains(fi.Extension))//找到一个图片(如果用户手贱把一个excel文件后缀改成jpeg没办法)
                {
                    this.listBox3_BMPFile.Items.Add(new MyImage(fi.FullName));
                }
            }
        }






        private void lstImage_Click(object sender, EventArgs e)
        {
            if (listBox3_BMPFile.SelectedItem == null)
            {
                return;
            }
            MyImage selectedImg = (MyImage)listBox3_BMPFile.SelectedItem;
            Image img = new Bitmap(selectedImg.Path);
            pictureBox1.Image = img;
        }
        private byte ircbmpflag = 1;

        private void button1_Click(object sender, EventArgs e)
        {
            int Width = pictureBox2.Size.Width;
            int Height = pictureBox2.Size.Height;
            Bitmap b = new Bitmap(Width, Height, PixelFormat.Format24bppRgb);
            Graphics gc = Graphics.FromImage((System.Drawing.Image)b);
            /// 设置绘图的颜色
            // 绘制圆，(0, 0)为左上角的坐标，radius为直径
            double ratio = 0.01;
            double area = Height * Width * ratio;
            int radius_V = (int)(Math.Pow(area / Math.PI, 0.5)) * 2;
            int radius_H = radius_V;
            int circle_H = Height / 2;
            int circle_V = Width / 2;
            double gray;
            Brush greenBrush;
            gray = 255; if (gray > 255) gray = 255;
            greenBrush = new SolidBrush(Color.FromArgb((int)gray, (int)(255 - gray), 0));
            // 绘制圆，(0, 0)为左上角的坐标，radius为直径
            gc.FillEllipse(greenBrush, circle_H, circle_V, radius_H, radius_V);
            pictureBox2.Image = b;


        }

        public class MyImage
        {
            public MyImage(string p)
            {
                this.Path = p;
            }
            public string Path { get; set; }
            public override string ToString()
            {
                if (Path == null)
                {
                    return null;
                }
                return System.IO.Path.GetFileName(this.Path);
            }
        }

        //-----------------------------------------
        #endregion


    }
}
